﻿using System;
using System.Web.Mvc;
using System.Xml.Linq;
using WeBlog.ActionResults;
using WeBlog.Interfaces;
using WeBlog.Models;

namespace WeBlog.Controllers
{
    public class ServicesController : ApplicationController
    {
        public ServicesController(IUnitOfWork unitOfWork) : base( unitOfWork )
        {            
        }

        public ActionResult Sitemap()
        {
            return new SitemapActionResult(UnitOfWork);
        }

        public ActionResult Feed( int? page = 1 )
        {
            var mgr = new SyndicationManager(UnitOfWork);
            return mgr.GetFeedResult(page);
        }

        public ActionResult Rsd()
        {
            var uri = ControllerContext.HttpContext.Request.Url;
            var homepageLink = new UriBuilder(uri.Scheme, uri.Host, uri.Port);
            var apiLink = new UriBuilder(uri.Scheme, uri.Host, uri.Port, "Services/MetaWeblogAPI.ashx");

            XNamespace rsdNamespace = "http://archipelago.phrasewise.com/rsd";
            var rsd = new XDocument(
                                new XElement(rsdNamespace + "rsd", new XAttribute("version", "1.0"),
                                    new XElement(rsdNamespace + "service",
                                        new XElement(rsdNamespace + "engineName", "WeBlog"),
                                        new XElement(rsdNamespace + "engineLink", "http://weblog.codeplex.com/"),
                                        new XElement(rsdNamespace + "homePageLink", homepageLink.Uri.ToString()),
                                        new XElement(rsdNamespace + "apis",
                                            new XElement(rsdNamespace + "api",
                                                new XAttribute("name", "MetaWeblog"),
                                                new XAttribute("preferred", "true"),
                                                new XAttribute("apiLink", apiLink.Uri.ToString()),
                                                new XAttribute("blogID", "1")))
                                    )
                                )
                            );

            return new XmlActionResult { Xml = rsd };
        }

    }
}
